package com.ruoyi.project.proxy;

import com.alibaba.fastjson.JSON;
import com.github.xingshuangs.iot.protocol.s7.enums.EPlcType;
import com.github.xingshuangs.iot.protocol.s7.service.S7PLC;
import com.ruoyi.framework.web.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.plc4x.java.DefaultPlcDriverManager;
import org.apache.plc4x.java.api.PlcConnection;
import org.apache.plc4x.java.api.messages.PlcReadRequest;
import org.apache.plc4x.java.api.messages.PlcReadResponse;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/openapi/proxy")
public class ProxyController {

    @PostMapping("visit-iot")
    public AjaxResult visitIoT(@RequestBody(required = true) HashMap<String,String> map){
        String address = map.get("address");
        String tag = map.get("tag");
        String type = map.get("type");

        log.info("{},{},{}" ,address,tag,type);
//        if(1==1)
//        return AjaxResult.success();

        String ret = "";
        S7PLC s7;
             s7 = new S7PLC(EPlcType.S200_SMART,address);
            if (type.equals("BOOL")) {
                ret = String.valueOf(s7.readBoolean(tag));
            } else if (type.equals("WORD")) {
                ret = String.valueOf(s7.readUInt16(tag));
            } else if (type.equals("DWORD")) {
                ret = String.valueOf(s7.readUInt32(tag));
            } else if (type.equals("REAL")) {
                ret = String.valueOf(s7.readFloat32(tag));
            } else if (type.equals("DOUBLE")) {
                ret = String.valueOf(s7.readFloat64(tag));
            }
            s7.close();
            return AjaxResult.success(ret);

    }

    @PostMapping("/visit-plc4x")
    public AjaxResult visitPlc4x(@RequestBody(required = true) HashMap<String,String> map){

        String connectstring = map.get("connectstring");
        String tagaddress = map.get("tagaddress");

        if(connectstring==null || tagaddress==null)
        {
            return AjaxResult.error("no params found");
        }

        log.info(connectstring);
        log.info(tagaddress);

//        if (1==1)
//            return JSON.toJSONString(map);

        try (PlcConnection connection = new DefaultPlcDriverManager().getConnection( connectstring )) {
            final PlcReadRequest.Builder builder = connection.readRequestBuilder();
            builder.addTagAddress("tag1", tagaddress );
            final PlcReadRequest readRequest = builder.build();
            final PlcReadResponse readResponse = readRequest.execute().get(5, TimeUnit.SECONDS);
            String ret = readResponse.getString("tag1");

            return AjaxResult.success(ret);
        }catch (Exception e){
            e.printStackTrace();
        }

        return AjaxResult.error();
    }

}
